package com.xxd.rpt2.config

import com.xxd.rpt2.Entity.Area
import com.xxd.rpt2.Entity.Department
import com.xxd.rpt2.Entity.Menu
import com.xxd.rpt2.Entity.Permission
import com.xxd.rpt2.Entity.Role
import com.xxd.rpt2.Entity.RoleType
import com.xxd.rpt2.Entity.User
import com.xxd.rpt2.repository.AreaRepository
import com.xxd.rpt2.repository.DepartmentRepository
import com.xxd.rpt2.repository.MenuRepository
import com.xxd.rpt2.repository.PermissionRepository
import com.xxd.rpt2.repository.RoleRepository
import com.xxd.rpt2.repository.RoleTypeRepository
import com.xxd.rpt2.repository.UserRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * @Author XuXd
 * @Description: 初始化菜单、用户等数据
 * @CreateDate: 11:49 2019-09-11
 * @Modified by: *
 */
@Configuration
class InitData {

    @Autowired
    UserRepository userRepository
    @Autowired
    DepartmentRepository departmentRepository
    @Autowired
    AreaRepository areaRepository
    @Autowired
    RoleRepository roleRepository
    @Autowired
    MenuRepository menuRepository
    @Autowired
    RoleTypeRepository roleTypeRepository
    @Autowired
    PermissionRepository permissionRepository
    @Bean
    def initDbData(){
        long flag = roleTypeRepository.count()
        if(flag<=0){
            initPermission()
            initMenu()
            initRoleType()
            initRole()
            initDepartment()
            initArea()
            initAdmin()
        }
    }

    def initDepartment(){
        departmentRepository.save(new Department(name: "ALL",code: "ALL"))
    }

    def initArea(){
        areaRepository.save(new Area(name: "ALL",code: "ALL"))
    }
    def initAdmin(){
        List<Role> role = roleRepository.findAll()
        Department department = departmentRepository.findAll().get(0)
        Area area = areaRepository.findAll().get(0)
        userRepository.save(new User(name: "管理员",code: "ADMIN",password: "1",department:department,
        area:area,roleList: role))
    }

    def initRoleType(){
        roleTypeRepository.save(new RoleType(name: "功能角色",code: "FUNC_ROLE"))
        roleTypeRepository.save(new RoleType(name: "数据角色",code: "DATA_ROLE"))
    }
    def initRole(){
        List<Menu> menuList = menuRepository.findAll()
        RoleType roleType = roleTypeRepository.findAll().get(0)
        Role role = new Role(name: "管理员",code: "ADMIN_ROLE",roleType: roleType,menuList: menuList)
        roleRepository.save(role)
    }

    def initPermission(){
        permissionRepository.save(new Permission(name: "查询",code: "query"))
    }
    def initMenu(){
        List<Permission> permissionList = permissionRepository.findAll()
        menuRepository.save(new Menu(name: "ROOT",code: "ROOT",permissionList: permissionList))
    }
}
